#! /usr/bin/python3
"""
Pomodoro timer

Counts down time for 1500 seconds == 1 Pomodoro
"""
__author__="gianni"
__date__ ="$23-ott-2009 15.43.50$"
from tkinter import *
import sys
import os
import time
from tkinter.messagebox import *
from tkinter.font import Font


class Wpomo(Frame):
    """
    Base widget for Pomodoro timer
    
    Display Pomodoro starter
    """

    def __init__(self, master):
        self._titolo="Pomodoro 3.01"
        self.masterframe=master
        Frame.__init__(self, master)

        self.masterframe.title(self._titolo)
        self.frame = Frame(master)
        self.frame.pack()
        self.isrunning=False
        self.timecounter=0
        self.callout="Pomodoro timer          "
        file=os.path.join((os.path.dirname(sys.argv[0])), 'pomodoro.gif')
        self.pict=PhotoImage(file=file)


        self.start = Button(self.frame, image=self.pict, command=self.start)
        self.start.pack(side=LEFT)
        self.w = Label(self.frame, text=self.callout)
        self.w.pack()

    def start(self):
        """
        Starts a Pomodoro
    
        Begin Pomodoro count-down
        """
        if self.isrunning: return
        myfont=Font(family='FreeSans', size=32, weight="bold")

        self.callout="Pomodoro running...     "
        self.w.destroy()
        self.w = Label(self.frame, text=self.callout)
        self.w.pack()
        self.isrunning=True
        self.timecounter=1500 # 1500 secondi == 25 minuti
        self.w.update()

        while self.timecounter>0:
            self.timecounter -= 1
            contatore=(self.timecounter/60)
            o = format(contatore, '3.1f')
            s = Label(self.frame, text=o, font=myfont, foreground="red")
            s.pack()
            self.masterframe.title(o + " minutes to go")
            self.frame.update()
            time.sleep(1)
            s.destroy()
            if not self.isRunning():
                self.masterframe.quit()
                break                   #senza questo non uscirebbe ma resterebbe nel loop
        # fine del pomodoro...
        self.callout="Pomodoro idle.               "
        s.destroy()
        self.w.destroy()
        self.w = Label(self.frame, text=self.callout)
        self.w.pack()
        self.w.update()
        if not self.isRunning(): return #aborted by user, nothing to do
        self.isrunning=False
        self.masterframe.title(self._titolo)
        # suona il campanello
        file=os.path.join((os.path.dirname(sys.argv[0])), 'ring.wav')
        if sys.platform.startswith('win'):
            from winsound import PlaySound, SND_FILENAME, SND_ASYNC
            PlaySound(file, SND_FILENAME|SND_ASYNC)
        elif sys.platform.find('linux')>-1:
            from wave import open as waveOpen
            from ossaudiodev import open as ossOpen
            s = waveOpen(file,'rb')
            (nc,sw,fr,nf,comptype, compname) = s.getparams( )
            dsp = ossOpen('/dev/dsp','w')
            try:
                from ossaudiodev import AFMT_S16_NE
            except ImportError:
                if byteorder == "little":
                    AFMT_S16_NE = ossaudiodev.AFMT_S16_LE
                else:
                    AFMT_S16_NE = ossaudiodev.AFMT_S16_BE
            dsp.setparameters(AFMT_S16_NE, nc, fr)
            data = s.readframes(nf)
            s.close()
            dsp.write(data)
            dsp.close()
#messaggio
        showinfo(self._titolo, "Your Pomodoro is elapsed.")


    def callkill(self):
        """
        Ask confirmation to quit
        """
        if self.isRunning():
            if askokcancel(self._titolo, "Pomodoro is running.\nDo you really wish to quit?"):
                self.isrunning=False
        else:
            self.masterframe.quit()

    def isRunning(self):
        return self.isrunning


class MyDialog:

    def __init__(self, parent):

        top = self.top = Toplevel(parent)

        Label(top, text="Value").pack()

        self.e = Entry(top)
        self.e.pack(padx=5)

        b = Button(top, text="OK", command=None)
        b.pack(pady=5)


if __name__ == "__main__":
    root = Tk()

    # create a menu
    menu = Menu(root)
    root.config(menu=menu)

    # applet
    app = Wpomo(root)


    #menu
    filemenu = Menu(menu)
    menu.add_cascade(label="File", menu=filemenu)
    filemenu.add_command(label="Exit", command=app.callkill)

    root.protocol("WM_DELETE_WINDOW", app.callkill)
    root.mainloop()
    root.destroy()
